package com.seckill.order.controller;

import com.seckill.order.pojo.Order;
import com.seckill.order.service.OrderService;
import com.seckill.util.JwtTokenUtil;
import com.seckill.util.Result;
import com.seckill.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.Map;

/**
 * @program: seckill-parent
 * @description: 订单相关的控制器, 其中下单是核心接口
 * @author: zhanghz001
 * @create: 2021-06-30 15:42
 **/
// @RestController
@RequestMapping("/order")
public class ZhzOrderController {
    
    @Autowired
    private OrderService orderService;
    
    @PostMapping("/add/{id}")
    public Result add(@PathVariable("id") String id,
                      @RequestHeader("Authorization") String authorization) {
        
        try {
            //判断是否登录,并且得到用户名
            Map<String, Object> objectMap = JwtTokenUtil.parseToken(authorization);
            String username = objectMap.get("username").toString();
            
            //封装订单
            Order order = new Order();
            order.setSkuId(id);
            order.setUsername(username);
            order.setTotalNum(1);
            Date date = new Date();
            order.setCloseTime(date);
            order.setUpdateTime(date);
            //添加订单
            int code = orderService.add(order);
            
            //通过生成订单的情况,进行返回
            switch (code) {
                case StatusCode.DECOUNT_NUM:
                    //库存不足
                    return new Result<>(false, StatusCode.DECOUNT_NUM, "库存不足");
                case StatusCode.ORDER_QUEUE:
                    //变成热卖商品
                    return new Result<>(true, StatusCode.ORDER_QUEUE, "抢购排队中");
                case StatusCode.ORDER_OK:
                    //商品抢购成功
                    return new Result<>(true, StatusCode.ORDER_OK, "商品抢购成功");
                default:
                    return new Result(false, StatusCode.ERROR, "添加订单失败");
            }
        } catch (Exception e) {
            //鉴权失败
            return new Result(false, StatusCode.TOKEN_ERROR, "请重新登录!");
        }
    }
}
